        # coding=utf-8
import requests
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
import os

g_code = 'sh510300'
g_total = 100000.0
round_suffix = 3
wait_sel_continue_days = 3
ma_array = [30, 60, 120]


def get_url(code, num):
    return 'http://money.finance.sina.com.cn/quotes_service/api/jsonp_v2.php/var=/CN_MarketData.getKLineData?symbol=%s&scale=240&ma=no&datalen=%d' % (code, num)


def get_code_name(code):
    return 'data/%s.txt' % code


def get_stock_history(code, num):
    r = requests.get(get_url(g_code, num))
    with open(get_code_name(g_code), "wb") as f:
        f.write(r.content)


def get_df(code):
    name = get_code_name(code)
    d = ""
    with open(name, "r") as f:
        d = f.read()
    df = pd.read_json(d)
    for it in ma_array:
        df[f'ma_{it}'] = df['close'].rolling(it).mean()
    return df

def double_ma(df):
    sum = g_total
    dc = df['close']
    day = df['day']
    buyed = False
    money = []
    stock_nums = 0
    buylast = 0.0
    sel_continue_days = 0

    for i in range(0, len(dc)):
        cur_price = round(dc[i], round_suffix)
        isna = [pd.isna(df[f'ma_{it}'][i]) for it in ma_array]
        if any(isna):
            money.append(round(sum, round_suffix))
            continue
        valid = [True if it == 0 else True if round(df[f'ma_{ma_array[max(it-1, 0)]}'][i], round_suffix) > round(df[f'ma_{ma_array[it]}'][i], round_suffix) else False for it in range(len(ma_array))] 
        valid.append(round(dc[i], round_suffix) > round(df[f'ma_{ma_array[0]}'][i], round_suffix))
        if all(valid):
            # buy
            sel_continue_days = 0
            if buyed is True:
                print(f'buy already at index={i} !!!!!!!!{day[i]}!!!!!!!!!!!')
                money.append(round(sum + stock_nums*cur_price, round_suffix))
                continue
            stock_nums = int(sum/cur_price/100)*100
            if stock_nums == 0:
                print(f'there is no money now...!!!!!!!!!!!!!!!!!!!!')
                money.append(round(sum, round_suffix))
                continue
            sum -= round(stock_nums*cur_price, round_suffix)
            buyed = True
            buylast = cur_price
            cur_ma_array_price = [round(df[f'ma_{it}'][i], round_suffix) for it in ma_array]
            print(f'buy {stock_nums} at price[{i}] {round(cur_price,round_suffix)} {day[i]} and cur_ma_array_price is {cur_ma_array_price} and valid is {valid}')
        else:
            # sel
            sel_continue_days += 1
            if buyed is True:
                if sel_continue_days >= wait_sel_continue_days:
                    tt = stock_nums*cur_price*0.999 + 10
                    sum += round(tt, round_suffix)
                    buyed = False
                    cost = round(stock_nums*(cur_price - buylast), round_suffix)
                    stock_nums = 0
                    cur_ma_array_price = [round(df[f'ma_{it}'][i], round_suffix) for it in ma_array]
                    print(f'sel {stock_nums} at price[{i}] {round(cur_price, round_suffix)} cost={cost} {day[i]} and cur_ma_array_price is {cur_ma_array_price}')
                else:
                    print(f'sel_continue_days {sel_continue_days} wait to sel index={i} !!!!!!!!{day[i]}!!!!!!!!!!!')

        money.append(round(sum + stock_nums*cur_price, round_suffix))
    df['money'] = money
    now_money = money[-1]
    print(f'now money is {now_money} and price from {round(dc[0], round_suffix)} to {round(dc[len(dc)-1], round_suffix)}')

    # money two ，一直持有
    sum = g_total
    money = []
    money.append(sum)
    cur_price = round(dc[0], round_suffix)
    stock_nums = int(sum/cur_price/100)*100
    sum -= round(stock_nums*cur_price, round_suffix)
    for i in range(1, len(dc)):
        cur_price = round(dc[i], round_suffix)
        money.append(round(sum + stock_nums*cur_price, round_suffix))

    df['money_always'] = money

    return df


def normalization(df):
    return (df-df.min())/(df.max()-df.min())


def simulate(code):
    df = get_df(code)

    double_ma(df)
    return
    # print(df)
    fig = plt.figure(1)
    fig.set(alpha=0.2)
    # 子图一
    plt.subplot2grid((3, 1), (0, 0))
    df.set_index("day", inplace=True)
    for it in ma_array:
        df[f'ma_{it}'].plot()
    df['close'].plot()
    str_ma_array = [f'ma_{it}' for it in ma_array]
    plt.title("{} and {} and {} and {} and close".format(*str_ma_array))
    plt.legend((*str_ma_array, 'close'), loc="lower left")
    # 子图二
    plt.subplot2grid((3, 1), (1, 0))
    # 归一化
    df["close_curve"] = normalization(df["close"])
    df["money_curve"] = normalization(df["money"])
    df["close_curve"].plot()
    df["money_curve"].plot()
    plt.title("close_curve and money_curve change")
    plt.legend(("close_curve", "money_curve"), loc="lower left")

    # 子图三
    plt.subplot2grid((3, 1), (2, 0))
    df["money_always"].plot()
    df["money"].plot()
    plt.title("money_always and money")
    plt.legend(("money_always", "money"), loc="lower left")

    plt.show()


def main():
    # get_stock_history(g_code, 1000)
    simulate(g_code)


if __name__ == '__main__':
    main()
